package com.hmall.trade.listener;

import com.hmall.api.client.item.ItemClient;
import com.hmall.api.client.pay.PayClient;
import com.hmall.api.dto.OrderDetailDTO;
import com.hmall.common.constants.MqConstants;
import com.hmall.common.domain.PayOrder;
import com.hmall.trade.domain.po.Order;
import com.hmall.trade.domain.po.OrderDetail;
import com.hmall.trade.mapper.OrderDetailMapper;
import com.hmall.trade.service.IOrderService;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * @Author 86157
 * @Date 2025/9/5 下午8:24
 */
@Component
public class OrderDelayMessageListener {

    @Autowired
    private  IOrderService oderService;
    @Autowired
    private PayClient payClient;
    @Autowired
    private ItemClient itemClient;
    @Autowired
    private OrderDetailMapper orderDetailMapper;

    @RabbitListener(bindings =@QueueBinding(
            value = @Queue(value = MqConstants.DELAY_ORDER_QUEUE_NAME, durable = "true"),
            exchange = @Exchange(value = MqConstants.DELAY_EXCHANGE_NAME, delayed = "true",type = ExchangeTypes.DIRECT),
            key = MqConstants.DELAY_ORDER_KEY
    ))
    public void listenOrderDelay(Long orderId) {
        //TODO 订单延迟消息处理
        Order order = oderService.getById(orderId);
        //查询订单状态
        if(order==null|| order.getStatus()!= 1){
            return;
        }
        //查询交易单状态
        //如果交易单支付成功（3），则返回
        PayOrder payOrder = payClient.queryByBizOrderNo(orderId);
        if(payOrder.getStatus()==3){
            oderService.markOrderPaySuccess(orderId);
            return;
        }
        //否则删除订单
        order.setStatus(5);
        oderService.updateById(order);
        //回滚库存
        List<OrderDetailDTO> orderDetails = oderService.getOrderDetails(orderId);
        itemClient.rollbackStock(orderDetails);
    }
}
